﻿/**
 * @file templatestylebutton.cpp
 * @author huangxb
 * @email 18228033207@163.com
 * @date 2025-04-16
 * @brief 模板样式button.
 */
#include "templatestylebutton.h"

#include <QStyleOption>
#include <QStylePainter>

/** @brief 边距 */
static const int MARGIN = 8;

CTemplateStyleButton::CTemplateStyleButton(QWidget *parent)
    : CTemplateStyleButton("", parent)
{

}

CTemplateStyleButton::CTemplateStyleButton(const QString &text, QWidget *parent)
    : QPushButton(parent)
{
    setText(text);
    setStyleSheet(R"(
QPushButton{background:transparent;border:none;}
QPushButton:hover{background:#ddd;border-radius:8px;})");
}

void CTemplateStyleButton::SetTemplateStyle(const QString &strTemplateName, const QString &strTemplateImage)
{
    m_strTemplateName = strTemplateName;
    m_strTemplateImage = strTemplateImage;
    m_spPixmapTemplate.reset(new QPixmap(strTemplateImage));
}

void CTemplateStyleButton::setText(const QString &strText)
{
    m_strText = strText;
}

QString CTemplateStyleButton::text() const
{
    return m_strText;
}

void CTemplateStyleButton::paintEvent(QPaintEvent */*event*/)
{
    /* 绘制QPushButton */
    QStylePainter sPainter(this);
    QStyleOptionButton option;
    initStyleOption(&option);
    sPainter.drawControl(QStyle::CE_PushButton, option);
    /* 绘制模板样式图片 */
    QRect rcImage = rect().marginsRemoved({MARGIN,MARGIN,MARGIN,MARGIN});
    int nImageHeight = m_spPixmapTemplate ? m_spPixmapTemplate->height() : 0;
    rcImage.setHeight(nImageHeight);
    if(m_spPixmapTemplate)
    {
        sPainter.drawItemPixmap(rcImage, Qt::AlignHCenter | Qt::AlignVCenter, *m_spPixmapTemplate);
    }
    /* 绘制模板样式名称 */
    QPalette paletteName = palette();
    paletteName.setColor(QPalette::Text, Qt::white);
    sPainter.drawItemText(rcImage, Qt::AlignHCenter | Qt::AlignVCenter, paletteName, true, m_strTemplateName, QPalette::Text);
    /* 绘制按钮文本 */
    QRect rcText = rect().marginsRemoved({MARGIN,MARGIN,MARGIN,0});
    rcText.setTop(rcImage.bottom());
    if(option.state & QStyle::State_MouseOver)
    {
        /* hover时才显示按钮文字 */
        QFont font = sPainter.font();
        font.setPixelSize(14);
        sPainter.save();
        sPainter.setFont(font);
        sPainter.drawItemText(rcText, Qt::AlignHCenter | Qt::AlignVCenter, palette(), true, m_strText);
        sPainter.restore();
    }
}
